import EditTable from '@/components/table/EditTable';
import type {
  ActionType,
  PageInfo,
  ProColumns,
  ProDescriptionsItemProps,
} from '@ant-design/pro-components';
import { PageContainer, ProDescriptions } from '@ant-design/pro-components';
import { FormattedMessage, useRequest } from '@umijs/max';
import { Drawer, message } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { OrganizationModel } from '../data';
import { createDept, deleteDept, deptList, getDeptList, updateDept } from '../service';
import EditForm from './EditForm';

const CurrentPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<OrganizationModel.organizationResponse>();
  const [selectedRows, setSelectedRows] = useState<OrganizationModel.organizationResponse[]>([]);
  const [organList, setOrganList] = useState<any[]>([]);
  const [pageInfo, setPageInfo] = useState<PageInfo>({ current: 1, pageSize: 20, total: 1 });
  const [messageApi, contextHolder] = message.useMessage();

  const { run: delRun } = useRequest(deleteDept, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('Deleted successfully and will refresh soon');
    },
    onError: () => {
      messageApi.error('Delete failed, please try again');
    },
  });

  useEffect(() => {
    const fetchDeptList = async () => {
      const msg = await deptList({});
      setOrganList(
        msg.result?.map((res) => ({
          label: res.name,
          value: res.code,
        })) || [],
      );
    };
    fetchDeptList();
  }, []);

  const columns: ProColumns<OrganizationModel.organizationResponse>[] = [
    {
      title: '部门编号',
      dataIndex: 'code',
      sorter: true,
      editable: false,
      render: (dom, entity) => (
        <a
          onClick={() => {
            setCurrentRow(entity);
            setShowDetail(true);
          }}
        >
          {dom}
        </a>
      ),
    },
    {
      title: '部门名称',
      dataIndex: 'name',
    },
    {
      title: '部门描述',
      dataIndex: 'description',
      search: false,
    },
    {
      title: '上级部门',
      dataIndex: 'parentCode',
      sorter: true,
      hideInForm: true,
      search: false,
      readonly: true,
      valueType: 'select',
      fieldProps: {
        options: organList,
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record, __, action) => [
        <a key="editable" onClick={() => action?.startEditable?.(record.code!)}>
          编辑
        </a>,
      ],
    },
  ];

  const handleSave = async (value: OrganizationModel.organizationResponse) => {
    if (value.code !== '0') {
      await updateDept(value);
    } else {
      await createDept(value);
    }
  };

  const handleRemove = useCallback(async (selectedRows) => {
    if (!selectedRows.length) {
      messageApi.warning('请选择删除项');
      return;
    }
    console.log(1231545645612313);
    await delRun({ codeList: selectedRows.map((row) => row.code!) });
  }, [selectedRows, delRun]);

  const handleRequest = async (params: OrganizationModel.organizationRequest) => {
    const msg = await getDeptList({
      name: params.name,
      pageNum: pageInfo.current,
      pageSize: pageInfo.pageSize,
    });
    setPageInfo({
      current: pageInfo.current,
      pageSize: pageInfo.pageSize,
      total: msg.result?.totalCount || 1,
    });
    return {
      data: msg.result?.items || [],
      total: msg.result?.totalCount || 0,
      success: true,
    };
  };

  return (
    <PageContainer>
      {contextHolder}
      <EditTable<OrganizationModel.organizationResponse, OrganizationModel.organizationRequest>
        removeRule={handleRemove}
        columns={columns}
        request={handleRequest}
        onOK={handleSave}
        renderToolBar={() => [
          <EditForm key="create" reload={actionRef.current?.reload} record={organList} />,
        ]}
      />
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow && (
          <ProDescriptions<OrganizationModel.organizationResponse>
            column={2}
            title={currentRow.name}
            request={async () => ({ data: currentRow || {} })}
            params={{ id: currentRow.code }}
            columns={columns as ProDescriptionsItemProps<OrganizationModel.organizationResponse>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default CurrentPage;
